﻿using Sprout.Core;
using Microsoft.Extensions.DependencyInjection;
using Quartz;
using System.Linq;
using System.Reflection;

namespace Sprout.Schedule
{
    public class RegisterService
    {
        public Assembly _assembly;
        public RegisterService()
        {
            _assembly = Assembly.GetExecutingAssembly();
        }
        /// <summary>
        /// 注册服务
        /// </summary>
        /// <param name="services"></param>
        public void Register(IServiceCollection services)
        {
            Register_Service(services);

            Register_Job(services);
        }
        /// <summary>
        /// 注册Service
        /// </summary>
        /// <param name="services"></param>
        public virtual void Register_Service(IServiceCollection services)
        {
            var ts = _assembly.GetTypes();

            foreach (var item in ts.Where(n => !n.IsInterface && !n.IsAbstract))
            {
                var serviceName = item.Name;
                var interfaceType = item.GetInterface($"I{serviceName}");
                //接口名 = I + 实现类名 
                if (interfaceType != null)
                {
                    services.AddTransient(interfaceType, item);
                }
            }
        }

        /// <summary>
        /// 注册Job
        /// </summary>
        /// <param name="services"></param>
        private void Register_Job(IServiceCollection services)
        {
            //反射自动注入
            var ts = _assembly.GetTypes();

            foreach (var item in ts.Where(n => !n.IsInterface && !n.IsAbstract))
            {
                var serviceName = item.Name;
                if (serviceName.LastIndexOf("Job") == (serviceName.Length - 3))
                {
                    if (item.GetInterface("IJob") == typeof(IJob))
                    {
                        services.AddTransient(item);
                    }
                }
            }
        }
    }
}
